<template>
  <div class="dashboard-container">
    <div class="dashboard-row">
      <el-card class="dashboard-card info-card">
        <div slot="header" class="card-header">
          <span>个人信息</span>
        </div>
        <div class="info-content">
          <div class="info-column">
            <div class="info-item">
              <span class="info-label">姓名：</span>
              <span class="info-value">{{ doctorData.dName || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">账号：</span>
              <span class="info-value">{{ doctorData.dId || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">性别：</span>
              <span class="info-value">{{ doctorData.dGender || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ doctorData.dPhone || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">身份证号：</span>
              <span class="info-value">{{ doctorData.dCard || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ doctorData.dEmail || "-" }}</span>
            </div>
          </div>
          <div class="info-column">
            <div class="info-item">
              <span class="info-label">职位：</span>
              <span class="info-value">{{ doctorData.dPost || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">科室：</span>
              <span class="info-value">{{ doctorData.dSection || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">挂号价格：</span>
              <span class="info-value">{{ doctorData.dPrice || "-" }}元</span>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ doctorData.dAvgStar || "0" }}</div>
              <div class="stat-label">平均评分</div>
            </div>
          </div>
        </div>
      </el-card>


      <el-card class="dashboard-card intro-card">
        <div slot="header" class="card-header">
          <span>个人简介</span>
        </div>
        <div class="introduction-content">
          {{ doctorData.dIntroduction || "暂无简介" }}
        </div>
      </el-card>
    </div>


    <div class="dashboard-row">
      <!-- 患者性别比例图表 -->
      <el-card class="dashboard-card chart-card">
        <div slot="header" class="card-header">
          <span>患者性别比例</span>
        </div>
        <div class="chart-container" ref="genderChart"></div>
      </el-card>

      <!-- 患者挂号统计图表 -->
      <el-card class="dashboard-card chart-card">
        <div slot="header" class="card-header">
          <span>患者挂号统计</span>
        </div>
        <div class="chart-container" ref="orderStatsChart"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import jwtDecode from "jwt-decode";
import { getToken } from "@/utils/storage.js";
import request from "@/utils/request.js";
import * as echarts from "echarts";

export default {
  name: "DoctorDashboard",
  data() {
    return {
      userId: "",
      doctorData: {},
      charts: {
        gender: null, 
        orderStats: null
      },
      genderData: [],
      orderStatsData: []
    };
  },
  methods: {
    requestDoctor() {
      request
        .get("admin/findDoctor", {
          params: {
            dId: this.userId,
          },
        })
        .then((res) => {
          if (res.data.status != 200)
            return this.$message.error("获取数据失败");
          this.doctorData = res.data.data;
          this.initCharts();
          this.loadGenderData(); 
          this.loadOrderStatsData();
        });
    },

    initCharts() {
      this.charts.gender = echarts.init(this.$refs.genderChart);
      this.charts.orderStats = echarts.init(this.$refs.orderStatsChart);
    },

    async loadGenderData() {
  try {
    const res = await request.get("order/orderGender");

    if (res.data.status === 200) {
      const genderData = res.data.data.map((item) => ({
        value: item.countGender,
        name: item.patient.pGender,
      }));

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: "vertical",
          right: 10,
          top: "center",
          textStyle: {
            color: "#606266",
          },
        },
        series: [
          {
            name: "性别比例",
            type: "pie",
            radius: '70%',
            center: ['40%', '50%'],
            data: genderData,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 2,
              color: (params) =>
                params.name === "男" ? "#4EA6DC" : "#DC4E9E",
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)',
              color: '#333',
              fontSize: 14
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 15,
              lineStyle: {
                width: 1,
                color: '#999'
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.charts.gender.setOption(option);
    } else {
      throw new Error(res.data.message || "获取性别数据失败");
    }
  } catch (error) {
    console.error("加载性别数据失败:", error);
    this.$message.error("加载性别数据失败");
    // 提供默认数据避免图表空白
    const option = {
      series: [
        {
          type: "pie",
          data: [
            { value: 50, name: "男" },
            { value: 50, name: "女" },
          ],
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)'
          },
          labelLine: {
            show: true
          }
        },
      ],
    };
    this.charts.gender.setOption(option);
  }
},
      async loadOrderStatsData() {
      try {
        const res = await request.get("patient/orderStats");
        
        if (res.data.status === 200) {
          this.orderStatsData = res.data.data;
          
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'value',
              axisLabel: {
                color: '#606266'
              },
              axisLine: {
                lineStyle: {
                  color: '#DCDFE6'
                }
              }
            },
            yAxis: {
              type: 'category',
              data: this.orderStatsData.map(item => item.patientName),
              axisLabel: {
                color: '#606266'
              },
              axisLine: {
                lineStyle: {
                  color: '#DCDFE6'
                }
              }
            },
            series: [{
              name: '挂号次数',
              type: 'bar',
              data: this.orderStatsData.map(item => item.orderCount),
              itemStyle: {
                color: function(params) {
                  const colorList = ['#4EA6DC', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
                  return colorList[params.dataIndex % colorList.length];
                },
                borderRadius: [0, 5, 5, 0]
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}次'
              }
            }]
          };
          
          this.charts.orderStats.setOption(option);
        } else {
          throw new Error(res.data.message || "获取挂号统计数据失败");
        }
      } catch (error) {
        console.error("加载挂号统计数据失败:", error);
        this.$message.error("加载挂号统计数据失败");
        // 提供默认数据避免图表空白
        const option = {
          series: [{
            type: 'bar',
            data: [3, 3, 3]
          }]
        };
        this.charts.orderStats.setOption(option);
      }
    },

    tokenDecode(token) {
      if (token !== null) return jwtDecode(token);
    },

    resizeCharts() {
      if (this.charts.gender) this.charts.gender.resize(); 
      if (this.charts.orderStats) this.charts.orderStats.resize();
    },
  },
  mounted() {
    window.addEventListener("resize", this.resizeCharts);
  },
  created() {
    this.userId = this.tokenDecode(getToken()).dId;
    this.requestDoctor();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeCharts);
    if (this.charts.gender) this.charts.gender.dispose(); 
    if (this.charts.orderStats) this.charts.orderStats.dispose();
  },
};
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  box-sizing: border-box;
}

.dashboard-row {
  display: flex;
  flex: 1;
  min-height: 0;
  margin-bottom: 16px;
}

.dashboard-row:last-child {
  margin-bottom: 0;
}

.dashboard-card {
  flex: 1;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.dashboard-card:last-child {
  margin-right: 0;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.info-card {
  min-width: 300px;
}

.info-content {
  flex: 1;
  display: flex;
  padding: 10px;
  overflow: auto;
}

.info-column {
  flex: 1;
  padding: 0 10px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-label {
  color: #909399;
  min-width: 80px;
  text-align: right;
  margin-right: 10px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.stat-item {
  text-align: center;
  margin-top: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #e6a23c;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.introduction-content {
  padding: 10px;
  line-height: 1.6;
  color: #606266;
  flex: 1;
  overflow: auto;
}

.chart-card {
  min-width: 300px;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .dashboard-row {
    flex-direction: column;
    margin-bottom: 0;
  }

  .dashboard-card {
    margin-right: 0;
    margin-bottom: 16px;
    min-height: auto;
  }

  .dashboard-card:last-child {
    margin-bottom: 0;
  }

  .info-content {
    flex-direction: column;
  }

  .info-column {
    padding: 0;
    margin-bottom: 16px;
  }

  .info-item {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>